package club.qweqwe.filter;

import club.qweqwe.GlobalConfig;
import club.qweqwe.exception.RequestException;
import club.qweqwe.model.form.Login;
import club.qweqwe.utils.ReflectUtils;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;

public class LoginFilter extends BaseFilter {
    @Override
    protected void doFilterEx(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException, IllegalAccessException, InvocationTargetException {
        String methodURI = request.getParameter(GlobalConfig.REQUEST_URI_METHOD_NAME);
        String clazzName = ReflectUtils.getClassName(Login.class);
        if (methodURI != null && clazzName.compareToIgnoreCase(methodURI) == 0) {
            Map<String, String> map = ReflectUtils.getFormBeanRequestParams(Login.class, request);
            Login login = new Login();
            BeanUtils.populate(login, map);
            if (!login.isValid())
                throw RequestException.REQUEST_ERROR_CODE_LOGIN_FORM_INFO;

            request.setAttribute(clazzName, login);
        }

        chain.doFilter(request, response);
    }
}
